package com.sun.tv;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;

import com.tools.MyLog;
import com.tools.SysInterfacePhone;

public class TVAdView extends RelativeLayout implements TVAd {
	protected ScheduledExecutorService loadAdScheduler = Executors
			.newScheduledThreadPool(1);
	// Runnable runnable = null;
	// protected ScheduledExecutorService loadAdScheduler =
	protected ScheduledExecutorService sendLogScheduler = Executors
			.newScheduledThreadPool(1);
	ScheduledFuture<?> future;
	TVAdType adView;
	String spaceId; // 广告位号
	// com.hdtmobile.imocha.AdViewInterface.IMochaAdType adType; // 广告类型
	String key; // 在Manage中存贮的ID号
	int serverId = TEST_MODE; // 服务器ID
	long updataTime = 30; // 刷新时间
	public String subId; // appid;
	boolean refresh = true; // 是否自动刷新。
	// boolean isScheduled = false; // 线程是否已开启 true:线程开启；false:线程关闭
	WeakReference<Context> contextWeakReference; // activity弱引用
	TVAdListener tvAdListener; // imocha回调监听器。
	AdConfig configFile; // 配置文件。

	static boolean deleteTimeoutShare = false;

	public TVAdView(Context context, String space) {
		super(context);
		init(context, space);
	}

	public TVAdView(Context context) {
		super(context);
		init(context, null);
	}

	

	public TVAdView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context, null);
	}

	// 初始化广告容器控件的相关配置代码
	private void init(Context context, String spaceId) {
		if (context == null) {
			MyLog.e("context is null");
			return;
		}
		// 设置广告位
		this.spaceId = spaceId;
		// 配备key,用于存储对象的键
		key = "" + this.hashCode();
		contextWeakReference = new WeakReference<Context>(context);
		if (TVAdManage.admanage== null) {
			TVAdManage.admanage = TVAdManage.getManage(context);
		}
		TVAdManage.admanage.pubAdViewWindow(key, this);
		adView = new BannerAd(context, key);
		if (!deleteTimeoutShare) {
			IMochaSharedPreferences sharedPreferences = new IMochaSharedPreferences();
			sharedPreferences.deletTimeOutRes((Activity) context);
			deleteTimeoutShare = true;
		}
		this.setVisibility(View.GONE);
		downloadAd();
	}

	public void downloadAd() {
		if (adView == null) {
			MyLog.e("called downloadAd mathfil, adview is null");
			return;
		}
		if (spaceId == null || spaceId.length() == 0) {
			MyLog.e("adSpace is null");
			return;
		}
		
		try {
			future = loadAdScheduler.schedule(new LoadAdRunnable(
					TVAdManage.admanage.getAdView(key)), 0,
					TimeUnit.SECONDS);
		} catch (Exception e) {
		}
	}

	@Override
	public void setTVAdListener(TVAdListener adListener) {
		tvAdListener = adListener;
	}

	@Override
	public void setRefresh(boolean refresh) {
		this.refresh = refresh;
	}
	@Override
	public void setUpdateTime(long updateTime) {
		if (updateTime > 30 && updateTime <= 120) {
			this.updataTime = updateTime;
		}
	}

	@Override
	public void destroy() {
		if (adView != null) {
			adView.iMochaDestroy();
		}

		if (future != null) {
			future.cancel(true);
			future = null;
		}
		loadAdScheduler.shutdownNow();
		loadAdScheduler.shutdown();
		loadAdScheduler = null;
		TVAdManage.admanage.adViewWindowMap.remove(key);
		System.gc();
	}

	public void setServerID(int serverid) {
		this.serverId = serverid;
	}

	// 更新广告容器里的广告内容
	public void updata(View view) {
		this.removeAllViews();
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(-1, -2);
		lp.addRule(RelativeLayout.CENTER_IN_PARENT);
		this.addView(view);
	}

	public void onEvent(IMochaEventCode eventCode) {
		if (tvAdListener != null) {
			TVAdManage.admanage.handler
					.post(new EventRunnable(this, eventCode));
		} else
			MyLog.v(" TVAdListener is null");
	}

	protected void sendImpressAdLog(AdConfig config) {
		if (config == null) {
			MyLog.e("send impress log fail,config is null");
			return;
		}
		onEvent(IMochaEventCode.adWillDisplay);
		ArrayList<String> listImp = config.tracks.listImp;
		for (String url : listImp) {
			url = SysInterfacePhone.invoker().replaceString(url, '[', ']',
					SysInterfacePhone.invoker().getRnd());
			sendLogScheduler.schedule(new PingUrlRunnable(url), 0,
					TimeUnit.SECONDS);
		}

	}

	protected void sendClickAdLog(AdConfig config) {
		onEvent(IMochaEventCode.adWillInteract);
		if (config == null) {
			MyLog.e("send Click Log fail,config is null");
			return;
		}
		ArrayList<String> listClk = config.tracks.listClk;
		for (String url : listClk) {
			url = SysInterfacePhone.invoker().replaceString(url, '[', ']',
					SysInterfacePhone.invoker().getRnd());
			sendLogScheduler.schedule(new PingUrlRunnable(url), 0,
					TimeUnit.SECONDS);
		}
	}

	/**
	 * @author hua.huang 发送日志线程
	 */
	private static class PingUrlRunnable implements Runnable {
		private String url;

		public PingUrlRunnable(String url) {
			this.url = url;
		}

		public void run() {
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(url);
			try {
				HttpResponse response = httpClient.execute(httpGet);
				int statusCode = response.getStatusLine().getStatusCode();
				MyLog.v("PingUrl:" + statusCode);
			} catch (ClientProtocolException e) {
				MyLog.e(e);
			} catch (IOException e) {
				MyLog.e(e);
			}
		}
	}

	private static class EventRunnable implements Runnable {
		TVAdView adview;
		IMochaEventCode eventcode;

		EventRunnable(TVAdView adview, IMochaEventCode eventcode) {
			this.adview = adview;
			this.eventcode = eventcode;
		}

		public void run() {
			adview.tvAdListener.onEvent(adview, eventcode);
		}
	}
}